<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #menu>
        <BasicTree
          :treeData="treeData"
          :checkStrictly="true"
          :fieldNames="{
            title: 'title',
            key: 'id',
          }"
          :selectable="false"
          checkable
          toolbar
          title="菜单分配"
          ref="treeRef"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './role.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTree, TreeActionType, TreeItem } from '/@/components/Tree';
  import { listToTree } from '/@/utils/helper/treeHelper';
  import MenuApi from '/@/api/sys/menu.class';
  import RoleApi from '/@/api/sys/role.class';
  import { isArray } from 'lodash-es';

  export default defineComponent({
    name: 'RoleDrawer',
    components: { BasicDrawer, BasicForm, BasicTree },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const treeData = ref<TreeItem[]>([]);
      const treeRef = ref<Nullable<TreeActionType>>(null);
      let menuList: any[] = [];

      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
        if (unref(treeData).length === 0) {
          // treeData.value = (await getMenuList()) as any as TreeItem[];
          treeData.value = listToTree(await getMenuList(), { pid: 'parentId' });
        }
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          //设置菜单选中状态
          const keys = data.record.menus.map((item: any) => item.id);
          treeRef?.value?.setCheckedKeys(keys);
          treeRef?.value?.setExpandedKeys(keys);
          setFieldsValue({
            ...data.record,
          });
        } else {
          treeRef?.value?.setCheckedKeys([]);
          treeRef?.value?.setExpandedKeys([]);
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          const _menus: any = treeRef.value?.getCheckedKeys();
          // TODO custom api
          let menus: any = null;
          if (_menus.checked && _menus.checked.length > 0) {
            menus = _menus.checked.map((item: number) => ({ id: item }));
          }
          if (isArray(_menus) && _menus.length > 0) {
            menus = _menus.map((item: number) => ({ id: item }));
          }
          values.menus = menus;
          if (unref(isUpdate)) {
            await new RoleApi().update(values);
          } else {
            await new RoleApi().create(values);
          }
          // console.log('values::', values);
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      async function getMenuList() {
        if (menuList.length > 0) return menuList;
        menuList = await new MenuApi().list();
        return menuList;
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        treeData,
        treeRef,
      };
    },
  });
</script>
